<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="pd.showSearch" label-width="68px">

      <el-form-item label="账户" prop="accountId">
        <el-select
            :style="{width: '150px'}"
            v-model="queryParams.accountId"
            placeholder="请选择账户来源"
            clearable>
          <el-option
              v-for="dict in fms_account"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"/>
        </el-select>
      </el-form-item>

      <el-form-item label="单据编号" prop="orderId">
        <el-input
            v-model="queryParams.orderId"
            placeholder="请输入单据编号"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>

      <el-form-item :label="pageLabel.partner" prop="partnerId">
        <DictSearch
            :dictName="dictPartner.dictName"
            :dictType="dictPartner.dictType"
            :isSingle="dictPartner.isSingle"
            :params="dictPartner.params"
            @selectd="dictSelectdParnter1"
        ></DictSearch>
      </el-form-item>

      <el-form-item :label="pageLabel.planTime" style="width: 308px">
        <el-date-picker
            v-model="pd.daterangePlanTime"
            value-format="YYYY-MM-DD"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item :label="pageLabel.executionTime" style="width: 308px">
        <el-date-picker
            v-model="pd.daterangeExecutionTime"
            value-format="YYYY-MM-DD"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['fms:bill:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="Edit"
            :disabled="pd.single"
            @click="handleUpdate"
            v-hasPermi="['fms:bill:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="pd.multiple"
            @click="handleDelete"
            v-hasPermi="['fms:bill:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
            v-hasPermi="['fms:bill:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar v-model:showSearch="pd.showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="pd.loading" :data="pd.billList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="编号" align="center" prop="id"/>
      <el-table-column label="类型" align="center" prop="type">
        <template #default="scope">
          <dict-tag :options="fms_bill_type" :value="scope.row.type"/>
        </template>
      </el-table-column>
      <el-table-column :label="pageLabel.partner" align="center" prop="partnerName"/>
      <el-table-column label="单据编号" align="center" prop="orderId"/>
      <el-table-column label="操作员" align="center" prop="userId"/>
      <el-table-column :label="pageLabel.receivableMoney" align="center" prop="receivableMoney"/>
      <el-table-column :label="pageLabel.money" align="center" prop="money"/>
      <el-table-column label="状态" align="center" prop="state">
        <template #default="scope">
          <dict-tag :options="sys_state" :value="scope.row.state"/>
        </template>
      </el-table-column>
      <el-table-column label="账户" align="center" prop="accountId">
        <template #default="scope">
          <dict-tag :options="fms_account" :value="scope.row.accountId"/>
        </template>
      </el-table-column>
      <el-table-column :label="pageLabel.planTime" align="center" prop="planTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.planTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="pageLabel.executionTime" align="center" prop="executionTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.executionTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark"/>
      <el-table-column label="更新人" align="center" prop="updateBy"/>
      <el-table-column label="更新时间" align="center" prop="updateTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.updateTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建者" align="center" prop="createBy"/>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column fixed="right" width="180" label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button v-if="scope.row.state!='0'" link type="primary" icon="Check" @click="handleAudit(scope.row)" v-hasPermi="['fms:bill:edit']">
            审核
          </el-button>
          <el-button v-if="scope.row.state!='0'" link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['fms:bill:edit']">
            修改
          </el-button>
          <el-button v-if="scope.row.state!='0'" link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                     v-hasPermi="['fms:bill:remove']">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="pd.total>0" :total="pd.total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize"
                @pagination="getList"/>

    <!-- 添加或修改财务单据对话框 -->
    <el-dialog :title="pd.title" v-model="pd.open" width="880px" append-to-body>
      <el-form ref="billRef" :model="form" :rules="rules" label-width="80px">

        <el-row>
          <el-col span="8">
            <el-form-item label="来往单位" prop="partnerId">
              <DictSearch
                  :dictName="dictPartner.dictName"
                  :dictType="dictPartner.dictType"
                  :isSingle="dictPartner.isSingle"
                  :params="dictPartner.params"
                  @selectd="dictSelectdParnter2"
              ></DictSearch>
            </el-form-item>
            <el-form-item label="合计金额" prop="totalMoney">
              <el-input :style="{width: '150px'}" v-model="form.totalMoney" placeholder="请输入合计金额"/>
            </el-form-item>
            <el-form-item label="分期收支" prop="byStages">
              <el-input :style="{width: '150px'}" v-model="form.byStages" placeholder="请输入分期期数"/>
            </el-form-item>
          </el-col>
          <el-col span="8">
            <el-form-item label="单据" prop="orderId">
              <DictSearch
                  :dictName="DictOrder.dictName"
                  :dictType="DictOrder.dictType"
                  :isSingle="DictOrder.isSingle"
                  :params="DictOrder.params"
                  @selectd="dictSelectdOrder"
              ></DictSearch>
            </el-form-item>
            <el-form-item label="优惠金额" prop="receivableMoney">
              <el-input :style="{width: '150px'}" v-model="form.discountMoney" placeholder="请输入优惠金额"/>
            </el-form-item>
            <el-form-item :label="pageLabel.planTime" prop="planTime">
              <el-date-picker clearable
                              :style="{width: '150px'}"
                              v-model="form.planTime"
                              type="date"
                              value-format="YYYY-MM-DD"
                              placeholder="请选择时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col span="8">
            <el-form-item label="账户" prop="accountId">
              <el-select
                  :style="{width: '150px'}"
                  v-model="form.accountId"
                  placeholder="请选择账户来源"
                  clearable>
                <el-option
                    v-for="dict in fms_account"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"/>
              </el-select>
            </el-form-item>
            <el-form-item :label="pageLabel.receivableMoney" prop="receivableMoney">
              <el-input :style="{width: '150px'}" v-model="form.receivableMoney" placeholder="请输入应收金额"/>
            </el-form-item>
            <el-form-item :label="pageLabel.money" prop="money">
              <el-input :style="{width: '150px'}" v-model="form.money" placeholder="请输入实收金额"/>
            </el-form-item>
          </el-col>
        </el-row>

        <!--        <el-form-item label="账户(收款/付款)" prop="accountId">
                  <el-input v-model="form.accountId" placeholder="请输入账户(收款/付款)" />
                </el-form-item>-->

        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">{{pd.title}}</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Bill">
import {listBill, getBill, delBill, addBill, auditBill, updateBill} from "@/api/fms/bill";

const {proxy} = getCurrentInstance();

const {
  sys_state,
  fms_account,
  fms_bill_type
} = proxy.useDict('sys_state', 'fms_account', 'fms_bill_type');

const dictPartner = reactive({
  dictName: "单据编号查找", // 设置单据编号查找的字典名称
  dictType: "md_partner",
  isSingle: true,
  params: {}
});
// 条件搜索的
function dictSelectdParnter1(dicts) {
  dicts.forEach(function (item) {
    queryParams.value.partnerId = item.dictValue;
  });
}
function dictSelectdParnter2(dicts) {
  dicts.forEach(function (item) {
    form.value.partnerId = item.dictValue;
    dictPartner.params.partnerId = item.dictValue;
  });
}

const DictOrder = reactive({
  dictName: "单据编号查找", // 设置单据编号查找的字典名称
  dictType: "wms_order_line_sum",
  isSingle: true,
  params: {
    fmsType: 'in',
    partnerId: null
  }
});
function dictSelectdOrder(dicts) {
  dicts.forEach(function (item) {
    form.value.orderId = item.dictValue;
    form.value.totalMoney = item.param1;
    form.value.discountMoney = item.param2;
    form.value.receivableMoney = item.param3;
  });
}

const pageLabel = reactive({
  partner: "",
  receivableMoney:"",
  money:"",
  planTime:"",
  executionTime:""
});

// 响应式变量用于存储后端传递的单据编号选项
const pd = reactive({
  billList: [],
  open: false,
  loading: true,
  showSearch: true,
  ids: [],
  single: true,
  multiple: true,
  total: 0,
  title: "",
  actionModel: 1,
  daterangePlanTime:[],
  daterangeExecutionTime:[]
});
// const billList = ref([]);
// const open = ref(false);
// const loading = ref(true);
// const showSearch = ref(true);
// const ids = ref([]);
// const single = ref(true);
// const multiple = ref(true);
// const total = ref(0);
// const title = ref("");
// const daterangePlanTime = ref([]);
// const daterangeExecutionTime = ref([]);
const route = useRoute();
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    type: null,
    partnerId: null,
    orderId: null,
    accountId: null,
    planTime: null,
    executionTime: null,
    quantity: null,
  },
  rules: {
    partnerId: [{
      required: true,
      message: "来往单位不能为空",
      trigger: "change"
    }],
    orderId: [{
      required: true,
      message: "单据id不能为空",
      trigger: "change"
    }],
    money: [{
      required: true,
      message: "金额不能为空",
      trigger: "change"
    }],
    receivableMoney: [{
      required: true,
      message: "金额不能为空",
      trigger: "change"
    }],
    planTime: [{
      required: true,
      message: "计划收支时间不能为空",
      trigger: "change"
    }],
    byStages: [{
      required: true,
      message: "账户不能为空",
      trigger: "change"
    }],
    accountId: [{
      required: true,
      message: "账户不能为空",
      trigger: "change"
    }]
  }
});

const {queryParams, form, rules} = toRefs(data);

/** 查询财务单据列表 */
function getList() {
  pd.loading = true;
  queryParams.value.params = {};
  if (null != pd.daterangePlanTime && '' != pd.daterangePlanTime) {
    queryParams.value.params["beginPlanTime"] = pd.daterangePlanTime[0];
    queryParams.value.params["endPlanTime"] = pd.daterangePlanTime[1];
  }
  if (null != pd.daterangeExecutionTime && '' != pd.daterangeExecutionTime) {
    queryParams.value.params["beginExecutionTime"] = pd.daterangeExecutionTime[0];
    queryParams.value.params["endExecutionTime"] = pd.daterangeExecutionTime[1];
  }
  listBill(queryParams.value).then(response => {
    pd.billList = response.rows;
    pd.total = response.total;
    pd.loading = false;
  });
}

// 取消按钮
function cancel() {
  pd.open = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    type: null,
    partnerId: null,
    orderId: 0,
    userId: null,
    totalMoney: 0,
    byStages: 1,
    receivableMoney: 0,
    discountMoney: 0,
    money: 0,
    accountId: null,
    planTime: null,
    executionTime: null,
    state: 1,
    remark: null,
    updateBy: null,
    updateTime: null,
    createBy: null,
    createTime: null
  };
  proxy.resetForm("billRef");
  form.value.type = route.query.type;
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  pd.daterangePlanTime = [];
  pd.daterangeExecutionTime = [];
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  pd.ids = selection.map(item => item.id);
  pd.single = selection.length != 1;
  pd.multiple = !selection.length;
}

/* 新增按钮操作 */
function handleAdd() {
  // 更新 dictType 属性的值
  reset();
  pd.open = true;
  pd.title = "添加财务单据";
  pd.actionModel =1;
}
/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || pd.ids
  getBill(_id).then(response => {
    form.value = response.data;
    pd.open = true;
    pd.title = "修改财务单据";
    pd.actionModel= 2;
    form.byStages = 0;
  });
}
//单据审核
function handleAudit(row) {
  reset();
  const _id = row.id || pd.ids
  getBill(_id).then(response => {
    form.value = response.data;
    pd.open = true;
    pd.title = "审核财务单据";
    pd.actionModel= 3;
    form.byStages = 0;
  });
}

/** 提交按钮 */
function submitForm() {
  if (pd.actionModel==1){
    addBill(form.value).then(response => {
      proxy.$modal.msgSuccess("新增成功");
      getList();
    });
  }else if (pd.actionModel==2){
    updateBill(form.value).then(response => {
      proxy.$modal.msgSuccess("修改成功");
      getList();
    });
  }else if (pd.actionModel==3){
    auditBill(form.value).then(response => {
      proxy.$modal.msgSuccess("已入账成功");
      getList();
    });
  }else {
    proxy.$modal.msgError("错误的actionModel类型")
  }
  pd.open = false;
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || pd.ids;
  proxy.$modal.confirm('是否确认删除财务单据编号为"' + _ids + '"的数据项？').then(function () {
    return delBill(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {
  });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('fms/bill/export', {
    ...queryParams.value
  }, `bill_${new Date().getTime()}.xlsx`)
}

function initPage() {
  queryParams.value = route.query;
  console.log(queryParams.value);
  if (queryParams.value.type == 1 || queryParams.value.type == 3) {
    pageLabel.partner = '支出单位';
    pageLabel.receivableMoney = "应收金额";
    pageLabel.money = "实收金额";
    pageLabel.planTime = "预收时间"
    pageLabel.executionTime = "实收时间";
    dictPartner.params.idCustomer = 0;
  } else if (queryParams.value.type == 2 || queryParams.value.type == 4) {
    pageLabel.partner = '收入单位';
    pageLabel.receivableMoney = "应付金额";
    pageLabel.money = "实付金额";
    pageLabel.planTime = "预付时间";
    pageLabel.executionTime = "实付时间";
    dictPartner.params.isSupplier = 0;
  } else if (queryParams.value.type == 5) {
    queryParams.value.partner = '来往单位'
  }
}

initPage();
getList();
</script>
